<script setup>
import { computed, onMounted, reactive, ref, watch } from "vue";
import { useRoute } from "vue-router";
import store from "@/store";
import SvgIcon from "../../svgIcon/index.vue";
const route = useRoute();
const permissionRoutes = store.getters["menu/permissionRoutes"];

const lang = computed(() => {
  return store.getters["webset/lang"];
});

const isShow = ref(true);

// 处理path
const handlePath = function (path) {
  return path.split("/").reduce((pre, cur) => {
    if (cur) {
      const lastItem = pre[pre.length - 1];
      if (lastItem) {
        pre.push(lastItem + "/" + cur);
      } else {
        pre.push("/" + cur);
      }
    }
    return pre;
  }, []);
};

// 查找路由
const findRoute = function (paths) {
  const selectRoutes = [];
  let tempRoutes = permissionRoutes;
  paths.forEach((it) => {
    const selectRoute = tempRoutes.find((pit) => {
      return pit.path === it;
    });
    if (selectRoute) {
      tempRoutes = selectRoute.children;
    }
    selectRoutes.push(selectRoute);
  });
  return selectRoutes;
};

const breadcrumb = reactive([]);

// 初始化面包屑
const initBreadCurmb = function () {
  isShow.value = false;
  breadcrumb.length = 0;
  breadcrumb.push(...findRoute(handlePath(route.path)));
  setTimeout(() => {
    isShow.value = true;
  }, 100);
};

onMounted(() => {
  initBreadCurmb();
});

watch(
  () => route.path,
  () => {
    if (
      route.path.startsWith("/redirect") ||
      ["/login", "/register", "/404"].includes(route.path)
    )
      return;
    return initBreadCurmb();
  }
);
</script>

<template>
  <transition name="breadcrumb" mode="out-in">
    <a-breadcrumb v-if="isShow">
      <a-breadcrumb-item href="/">
        <SvgIcon name="homeOutlined" />
      </a-breadcrumb-item>
      <a-breadcrumb-item v-for="item in breadcrumb">
        <SvgIcon :name="item.meta?.icon" />
        {{ lang === "en" ? item.meta?.enTitle : item.meta?.title }}
      </a-breadcrumb-item>
    </a-breadcrumb>
  </transition>
</template>

<style lang="less" scoped>
.breadcrumb-leave-active,
.breadcrumb-enter-active {
  transition: all 0.5s;
}

.breadcrumb-enter-from {
  opacity: 0;
  transform: translateY(-50px);
}

.breadcrumb-leave-to {
  opacity: 0;
  transform: translateY(20px);
}
</style>